package main

import (
	"context"
	"fmt"
	"gitee.com/jinmingzhi/eth-learn/pkg/ethtool"
	"github.com/ethereum/go-ethereum/core/types"
	"math/big"
	"time"
)

var (
	url    = "http://localhost:8545"
	ctx    = context.Background()
	client *ethtool.Client
)

func main() {
	var err error
	client, err = ethtool.Dial(url)
	assert(err)
	accounts, err := client.EthAccounts(ctx)
	assert(err)

	// pull
	go pull()

	//
	go push()

	timer := time.NewTicker(time.Second * 5)
	for range timer.C {
		msg := map[string]interface{}{
			"from":  accounts[0],
			"to":    accounts[1],
			"value": big.NewInt(1000), // 1000 wei
		}
		hash, err := client.EthSendTransaction(ctx, msg)
		assert(err)
		fmt.Println("SendTransaction hash:", hash.Hex())
	}
}

// http 轮询
func pull() {
	filterId, err := client.EthNewBlockFilter(ctx)
	assert(err)

	timer := time.NewTicker(time.Second * 2)
	for range timer.C {
		hashes, err := client.EthGetFilterChanges(ctx, filterId)
		assert(err)
		for _, hash := range hashes {
			block,_ := client.EthGetBlockByHash(context.Background(),hash)//查询区块数据
			for _,tx := range block.Transactions() {
				fmt.Println("pull block txid: ", tx.Hash().Hex())                   //显示交易哈希
			}
			fmt.Println("pull block hash:", hash.Hex())
		}
	}
}

// ws 推送
func push() {
	client, err := ethtool.Dial("ws://localhost:8545")
	assert(err)

	headers := make(chan *types.Header)
	sub, err := client.SubscribeNewHead(context.Background(), headers)
	assert(err)

	for {
		select {
		case err := <-sub.Err():
			panic(err)
		case header := <-headers:
			fmt.Println("push block hash: ", header.Hash().Hex())
		}
	}
}

func assert(err error) {
	if err != nil {
		panic(err)
	}
}
